package com.zhaojun.netty.helloworld;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;

public class Client {

    public static void main(String[] args) {

        EventLoopGroup  workerGroup=new NioEventLoopGroup();
        Bootstrap  bootstrap=new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()/*.addLast(new ChannelOutboundHandlerAdapter(){
                    @Override
                    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                        ChannelFuture f = ctx.writeAndFlush(msg, promise);
                    }


                })*/.addLast(new ChannelInboundHandlerAdapter(){
                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        super.channelReadComplete(ctx);
                        System.out.println("sasa");
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf receiveBuf= (ByteBuf) msg;
                        int n=receiveBuf.readableBytes();
                        byte[] bytes=new byte[n];
                        receiveBuf.readBytes(bytes);
                        System.out.println(new String(bytes));

//                        ctx.writeAndFlush()

                        ReferenceCountUtil.release(receiveBuf);
                        ByteBuf sendMsg = Unpooled.wrappedBuffer("你好".getBytes("utf-8"));
                        ChannelFuture f = ctx.writeAndFlush(sendMsg);
//                        f.addListener(ChannelFutureListener.CLOSE);
                    }
                });
            }
        });

        try {
            ChannelFuture f=bootstrap.connect("127.0.0.1",8888).sync();//当连接上服务端 当前通道在服务端注册激活 如果关闭通道也就关闭了 服务与客户端之间的通信渠道


            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
